const koa = require("koa");
const koaRouter = require("@koa/router");

const jwt = require("jsonwebtoken");

const app = new koa();

const userRouter = new koaRouter({ prefix: "/users" });

const secretKey = `ksfadhjsadf`;

userRouter.get("/login", (ctx, next) => {
  const payload = { id: 123, name: "456" };
  //颁发token
  const token = jwt.sign(payload, secretKey, { expiresIn: 60 });

  ctx.body = {
    code: 200,
    token,
    message: "登录成功",
  };
});

userRouter.get("/list", (ctx, next) => {
  //获取客户端携带过来的token
  const authorization = ctx.headers.authorization;
  const token = authorization.replace(`Bearer `, "");

  //验证token
  const result = jwt.verify(token, secretKey);
  try {
    ctx.body = {
      code: 200,
      data: [
        { id: 123, name: "hahah" },
        { id: 456, name: "嘻嘻" },
      ],
    };
  } catch (error) {
    ctx.body = {
      code: 403,
      message: "无效token已经过期",
    };
  }
});

app.use(userRouter.routes());
app.use(userRouter.allowedMethods());

app.listen("9000", () => {
  console.log("koa服务器开启");
});
